gGress= [];
gCheckFields = ["roomno",  "ddepdate", "darrdate","cguestname", "csex", "dbirthday", "cidtype", "cidnumber", "caddress", "ctel", "cemail", "cmobile", "cdescription"];
gDepositRate = 0.3;
var groomfield = "iroomid", garrfield = "arrorigdate", gdepfield = "deporigdate", groomnofield = "roomno";


gCheckInChanged = false;
gMemberDiscount = 0; //会员消费金额折扣

gUser = {
  userId:null,
  userName:null
}

gOrderHandler = {
   txtAccount:{itemId:null, itemCode:null, itemDesc:null, isConsume:true},
   txtCash:{itemId:"2010", itemCode:"现金", itemDesc:"现金", isConsume:true, category:"D"},
   txtCashOut:{itemId:"2009", itemCode:"现金支出", itemDesc:"现金支出", isConsume:true, category:"C"},
   txtCard:{itemId:"2130", itemCode:"银行卡", itemDesc:"银行卡", isConsume:true, category:"D"},
   txtCardOut:{itemId:"1003", itemCode:"Bank card out", itemDesc:"银行卡支出", isConsume:true, category:"D"},
   txtProduct:{itemId:"1004", itemCode:"Items", itemDesc:"商品", isConsume:true, category:"D"},
   txtCompensate:{itemId:"1005", itemCode:"Compensate", itemDesc:"赔偿", isConsume:true, category:"C"},
   txtRent:{itemId:"1006", itemCode:"Rent", itemDesc:"日租房费", isConsume:true, category:"C"},
   txtOthers:{itemId:"1007", itemCode:"Others", itemDesc:"其它杂项", isConsume:true, category:"C"},
   txtPartComplete:{isComplete:true, isAll:false},
   txtComplete:{isComplete:true, isAll:true},   
   txtTransfer:{isTransfer:true},
   txtRevese:{isReverse:true},
   txtWorkAccount:{isWorkAccount:true}
}


//取某行的金额（包括commision、rootrate、rate)
function getLineAmt(cellText, ety, rowIdx, cellIdx, grid, fieldName){
   var x = fieldName?fieldName:this.fieldName;
   var fName = "";
   if (x == "commision"){
      fName = "ncommissionprice";
   }else if ( x == "nroomrate"){
      fName = "nroomrate";
   }else if ( x == "nrate"){
      fName = "nrate";
   }
   var schedule = ety.getPropertyByFieldName("schedules");
   if (!schedule){
     schedule = ety.getPropertyByFieldName("schedules");
     return "";
   }
   
   var entities = getDatasetEntities(schedule);
   var result = 0;
   for(var i = 0; i < entities.length; i++){
     result += Number(entities[i].getPropertyByFieldName(fName));
   }
   return Math.round(result * 10000) / 10000;
}

//取日期间的距离
function dayDiff(start, end){


   var x1 = toBusinessDate(stringToDate(start, 'yyyy-MM-dd HH:mm:ss')).getTime(), 
       x2 = toBusinessDate(stringToDate(end, 'yyyy-MM-dd HH:mm:ss')).getTime();
   
   if (x1 > x2){
     return "";
   }
   
   var result = 0;
   
   while (x1 <= x2){
      result++;
      x1 += 1 * 24 * 60 * 60 * 1000;
   }

   return result;
   
}

//取总的金额（包括commision、rootrate、rate)
function getTotalAmt(fieldName, target){
  var dataset = $id("gress").dataset;
  var entities = getDatasetEntities(dataset);
  var result = 0;
  for(var i = 0; i < entities.length; i++){
    if (entities[i].status == Entity.STATUS_DELT || entities[i].status == Entity.STATUS_HIDDEN){
       continue;
    }
    
    if ((entities[i].getProperty("biscancelgres") + "").toUpperCase() == "Y"){
      continue;
    }
    
    
    result += getLineAmt(null, entities[i], 0, 0, null, fieldName);
  }
  var v = (Math.round(result * 10000) / 10000) + "";
  $id(target).value = v;
  return v;
}

//将自然日期转换为营业日期(不带时分秒)
function toBusinessDate(date){
   var year =  date.getFullYear(),
       month = date.getMonth();
       day = date.getDate();
   
   var target = new Date(year, month, day, 12, 0, 0);
   
   if (date.getTime() > target.getTime()){//如果是12点钟之后，就划入当前营业日期
      return new Date(year, month, day);  
   }else{//如果划入前一个营业日期
      var down = new Date(date.getTime() - 24 * 60 * 60*1000);
      return new Date(down.getFullYear(), down.getMonth(), down.getDate());
   }
}


//计算房晚数
function getDayCount(cellText, ety, rowIdx, cellIdx, grid){
   if (!ety.getPropertyByFieldName("arrorigdate") || !ety.getPropertyByFieldName("deporigdate")){
      return "";
   }

   var x1 = toBusinessDate(stringToDate(ety.getPropertyByFieldName("arrorigdate"), 'yyyy-MM-dd HH:mm:ss')).getTime(), 
       x2 = toBusinessDate(stringToDate(ety.getPropertyByFieldName("deporigdate"), 'yyyy-MM-dd HH:mm:ss')).getTime();
   
   if (x1 > x2){
     return "";
   }
   
   var result = 0;
   
   while (x1 <= x2){
      result++;
      x1 += 1 * 24 * 60 * 60 * 1000;
   }
   
   //return ((x2.getTime() - x1.getTime() + 1 * 24 * 60 * 60 * 1000) / 3600000 / 24);
   return result;
}


function getCommision(cellText, ety, rowIdx, cellIdx, grid){
  return getLineAmt(cellText, ety, rowIdx, cellIdx, grid, 'commision');
}

//查找隐藏的客单
function getGress(key){
   for(var i = 0; i < gGress.length; i++){
      if (gGress[i].localkey == key){
         return gGress[i];
      }
   }
}

//查找隐藏客单的序号
function getGressIdx(key){
   for(var i = 0; i < gGress.length; i++){
      if (gGress[i].localkey == key){
         return i;
      }
   }
   return null;
}

//按照序号查找entity
function getGressEntity(key){
  var dataset = $id("gress").dataset;
  if (!dataset){
    return null;
  }
  var entities = getDatasetEntities(dataset);
  if (!entities){
    return null;
  }
  for(var i = 0; i < entities.length; i++){
  
    if (entities[i].status == Entity.STATUS_DELT || entities[i].status == Entity.STATUS_HIDDEN){
         continue;
    }
        
    if (entities[i].getPropertyByFieldName("localkey") == key){
       return entities[i];
    }
  }
  return null;
}

//获取已经维护的某个日期的实体
function getScheduleByDate(bdate, ety){
   var schedule = ety.getPropertyByFieldName("schedules");
   if (!schedule){
      return null;
   }
   schedule = schedule.getEntities();
   for(var i = 0; i < schedule.length; i++){
      if (schedule[i].getPropertyByFieldName("dbusinessdate") == bdate){
         return schedule[i];
      }
   }
   return null;
}

//客单新增后设置临时主键
function afterGressAdd(e){
  var ety = $id("gress").getEntity(e);
  var x = (new Date()).getTime();
  ety.setPropertyByFieldName("localkey", x);
  ety.setPropertyByFieldName("cstatus", "R");
  ety.setPropertyByFieldName("cmodifystatus", "R");
  gGress[gGress.length] = {
     localkey:x,
     inited:false
  }
}

//客单删除后的处理
function afterGressDelete(row){
   var localKey  = $id("gress").getEntity(row).getPropertyByFieldName("localkey") + "";
   var idx = getGressIdx(localKey);
   if (idx){
     gGress.splice(idx, 1);
   }
   //刷新从表显示
   sumAmount();
}

//客单字段修改之后的处理
function afterGressEdit(text, value, grid){
   var field = grid.activeField.fieldName;
   

   if (field != "roomno" && field != "arrorigdate" && field != "deporigdate" && field != "cnewroomno" && field != "dnewarrdate" && field != "dnewdepdate"){
      return;
   }

   var ety =  grid.getActiveEntity();
   var key = ety.getPropertyByFieldName("localkey");
   var gress = getGress(key);
   
   if (field == "roomno" && grid.activeEntity.getProperty("iroomid") ==  gress.roomid){
     return;
   }

   if (field == "arrorigdate" && text ==  gress.orginarrdate){
     return;
   }
   
   if (field == "deporigdate" && text ==  gress.orginleavedate){
     return;
   }
   
   if (field == "cnewroomno" && grid.activeEntity.getProperty("inewroomid") ==  gress.newroomid){
     return;
   }

   if (field == "dnewarrdate" && text ==  gress.newarrdate){
     return;
   }
   
   if (field == "dnewdepdate" && text ==  gress.newdepdate){
     return;
   }
      
   //如果发生修改，将初始化标志修改
   gress.inited = false;
   gress.roomid = grid.activeEntity.getPropertyByFieldName("iroomid");
   gress.orginarrdate = grid.activeEntity.getPropertyByFieldName("arrorigdate");
   gress.orginleavedate = grid.activeEntity.getPropertyByFieldName("deporigdate");
   
   gress.newroomid = grid.activeEntity.getPropertyByFieldName("inewroomid");
   gress.newarrdate = grid.activeEntity.getPropertyByFieldName("dnewarrdate");
   gress.newdepdate = grid.activeEntity.getPropertyByFieldName("dnewdepdate");
      
}

//初始化隐藏的数据集合
function initGress(){
  var dataset = $id("gress").dataset;
  if (!dataset){
    return;
  }
  var entities = dataset.getEntities();
  if (!entities){
    return;
  }
    
  for(var i = 0; i < entities.length; i++){
     var x = (new Date()).getTime();
     entities[i].setPropertyByFieldName("localkey", x);
     gGress[gGress.length] = {localkey:x,
      						  gressid:entities[i].getPropertyByFieldName("igresid"),
      						  roomid:entities[i].getPropertyByFieldName("iroomid"),
      						  orginarrdate:entities[i].getPropertyByFieldName("arrorigdate"),
      						  orginleavedate:entities[i].getPropertyByFieldName("deporigdate"),
      						  newroomid:entities[i].getPropertyByFieldName("inewroomid"),
      						  newarrdate:entities[i].getPropertyByFieldName("dnewarrdate"),
      						  dnewdepdate:entities[i].getPropertyByFieldName("dnewdepdate"),
      						  inited:true};
  }
  
  //计算总计金额
  getTotalAmt("nrate", "txtPriceAmt");
  
  //计算原价格总额
  getTotalAmt("nroomrate", "txtOriginAmt");
  
  
  //计算佣金总额
  getTotalAmt("commision", "txtCommision");
  
  //折扣总额
  var a = Number($id("txtOriginAmt").value), b = Number($id("txtPriceAmt").value);
  var d = Math.round((a - b) * 10000) / 10000;
  $id("txtDiscount").value =  d < 0 ? "0": d;
  
  //预付款金额
  $id("txtPrepayAmt").value = Math.round((Number($id("txtPriceAmt").value) * Number($id("txtPrepayPercent").value)) * 10000) / 10000 + "";
    
    
}

//采用队列方式刷新，产生房租计划
function gressRefreshQueue(){
  var x = null;
  for(var i = 0; i < gGress.length; i++){
     if (gGress[i].inited == false && ((gGress[i].orginarrdate && gGress[i].orginleavedate && gGress[i].roomid) || (gGress[i].newarrdate && gGress[i].newdepdate && gGress[i].newroomid))){
        x = gGress[i];
        break;
     }
  }
  
  if (x == null){  //如果没有数据需要处理,就设置两秒后自动扫描
     setTimeout(gressRefreshQueue, 2000);
  }else{//如果有数据需要处理，就自动产生
     x.inited = true;
     var a = getGressEntity(x.localkey);
     parseGress(x.newroomid ? x.newroomid: x.roomid, 
                x.newarrdate ? x.newarrdate: x.orginarrdate, 
                x.newdepdate ? x.newdepdate:x.orginleavedate,  
                x.localkey,
                a.getPropertyByFieldName("igresid"));
  }

}

//将日期分解，产生房租计划
function parseGress(xroomId, xstartDate, xendDate, xlocalKey, xgresId){

  var x1 = toBusinessDate(stringToDate(xstartDate,'yyyy-MM-dd HH:mm:ss')), x2 = toBusinessDate(stringToDate(xendDate, 'yyyy-MM-dd HH:mm:ss'));
  var x = {
     roomId:xroomId,
     startDate:xstartDate,
     endDate:xendDate,
     dayCount:((x2.getTime() - x1.getTime() + 1 * 24 * 60 * 60 * 1000) / 3600000 / 24),
     memberId:$name("weordertasks/cbookmemberid").value,
     gresId:xgresId?xgresId:''
  };
  
  jrq(function(a){
       calGressSchedule(eval("(" + a + ")"), xroomId, xstartDate, xendDate, xlocalKey);
       gressRefreshQueue(); //继续扫描
      }, 
      "POST", 
      JSON.stringify(x), 
      "com.hms.OrderMgr.priceUtils.queryRoomRate.biz.ext", 
      true);
}


//计算客单房租计划
function calGressSchedule(schedule, srcRoomId, srcFrom, srcTo, key){
  var ety = getGressEntity(key);
  if (!ety){
    //如果该行Entity已经不存在，就删除
    var idx = getGressIdx(key);
    gGress.splice(idx, 1);
    setTimeout(gressRefreshQueue, 2000);
    return;
  }
      
  //比较关键属性是否相同，如果不同，就重新刷新
  if (ety.getPropertyByFieldName(groomfield) != srcRoomId ||
      ety.getPropertyByFieldName(garrfield) != srcFrom ||
      ety.getPropertyByFieldName(gdepfield) != srcTo){
      var x = getGress(key);
      x.roomid = ety.getPropertyByFieldName(groomfield);
      x.orginarrdate = ety.getPropertyByFieldName(garrfield);
      x.orginleavedate = ety.getPropertyByFieldName(gdepfield);
      parseGress(x.roomid, x.orginarrdate, x.orginleavedate, key, ety.getPropertyByFieldName("igresid"));
      return;
  }
   
  var x = getGress(key);
  if (x.inited = false){//如果中间被重新刷新过，就不处理
     return;
  }
  
  //判断房间是否被占用,如果被占用就设置错误标志
  if (schedule.errCode == "E"){
    x.errCode = "E";
    x.errMsg = schedule.errMsg;   
    alert("房号" + ety.getProperty(groomnofield) + '在指定日期范围内已经被客单' + schedule.errMsg + '占用，不能预订!');
    x.inited = true;
    return;
  }
  
  x.errCode = null;
  x.errMsg = null;
  
  //删除超出日期范围的数据
  var sches = ety.getPropertyByFieldName("schedules");
  var bSrcTo = dateToString(toBusinessDate(stringToDate(srcTo, 'yyyy-MM-dd HH:mm:ss')));
  var bSrcFrom = dateToString(toBusinessDate(stringToDate(srcFrom, 'yyyy-MM-dd HH:mm:ss')));
  if (sches != null){
     var schEty = sches.getEntities();
     for(var i = schEty.length -1; i >= 0; i--){
       if (schEty[i].getPropertyByFieldName("dbusinessdate") > bSrcTo || schEty[i].getPropertyByFieldName("dbusinessdate") < bSrcFrom){
         sches.removeEntity(schEty[i], true);
       }
     }
  }

  var vFrom = stringToDate(bSrcFrom, 'yyyy-MM-dd').getTime(), vTo = stringToDate(bSrcTo, 'yyyy-MM-dd').getTime();
  var vDate = stringToDate(bSrcFrom, 'yyyy-MM-dd');
  var count = 0;
  while (vFrom <= vTo){
     var vBDate = stringToDate(bSrcFrom, 'yyyy-MM-dd');
     vBDate.setDate(vDate.getDate() + count);
     
     //从返回的房价信息中获取房价或标准房价
     var p = getPrice(dateToString(vBDate), schedule, bSrcFrom, bSrcTo);
     p.iroomid = srcRoomId;
     
     //检查是否存在
     var sEty = getScheduleByDate(dateToString(vBDate, 'yyyy-MM-dd'), ety);
     if (!sEty){
        var s = ety.getProperty("schedules");
        if (s){
          s.addEntity(Json2Entity(p));
        }
     }else{
        sEty.setProperty("nroomrate", p.nroomrate);
        sEty.setProperty("nratedisount", p.nratedisount);     
        sEty.setProperty("nmemberdiscount", p.nmemberdiscount);   
        sEty.setProperty("commisionRate", p.commisionRate);                    
     }
     
     count++;
     vFrom += 1 * 24 * 60 * 60 * 1000;
  }

  //刷新佣金显示
  $id("gress").afterEdit = null;
  try{
     ety.setPropertyByFieldName("commision", getCommision("", ety, null, null, $id("gress")));
     $id("gress").afterEdit = afterGressEdit;
  }catch(e){
     $id("gress").afterEdit = afterGressEdit;
  }
  //....
  
  getGress(key).inited = true;
  
  //如果网格的当前实体正好是要刷新的数据，就重新显示孙表网格
  var curr = $id("gress").getActiveEntity();
  if (curr && curr.getPropertyByFieldName("localkey") ==  ety.getPropertyByFieldName("localkey")){
    $id("grdSchedule").refresh();
  }
  
  //计算总计金额
  getTotalAmt("nrate", "txtPriceAmt");
  
  //计算原价格总额
  getTotalAmt("nroomrate", "txtOriginAmt");
  
  
  //计算佣金总额
  getTotalAmt("commision", "txtCommision");
    
  
  //折扣总额
  var d = Math.round((Number($id("txtOriginAmt").value) - Number($id("txtPriceAmt").value)) * 10000) / 10000;
  $id("txtDiscount").value = d < 0 ? "0" : d + "";
  
  //预付款金额
  $id("txtPrepayAmt").value = Math.round((Number($id("txtPriceAmt").value) * $id("txtPrepayPercent").value) * 10000) / 10000 + "";
  
}

//从价目表中获取房价、折扣、佣金等信息
function getPrice(busiDate, list, vstart, vend){
   var result = {nroomrate:0, 
                 nrate:0, 
                 nroomrate:0,
                 ncommissionprice:0, 
                 nratedisount:1, 
                 nmemberdiscount:1,
                 dbusinessdate:busiDate}, 
       found = false;

   //算标准房价
   for(var i = 0; i < list.rates.length; i++){
      if (list.rates[i].dbusinessdate == busiDate){
         found = true;
         result.nroomrate = Number(list.rates[i].nroomrate);
         break;
      }
   }
   if (found == false){
      result.nroomrate = Number(list.basePrice);
      getDiscount(result, dayDiff(vstart, vend), result.nroomrate, list.charge)
   }else{
      if ((list.rates[i].bisdiscount||"").toUpperCase() != "N"){
        //从折扣表中查找数据，计算折扣--包括天数折扣和价格折扣
        getDiscount(result, dayDiff(vstart, vend), result.nroomrate, list.charge)
      }
   }
   
   //result.nroomrate = Math.round(result.nroomrate * (result.nratedisount) * (result.nmemberdiscount) * 10000) / 10000;
   result.nrate  = Math.round(result.nroomrate * (result.nratedisount) * (result.nmemberdiscount) * 10000) / 10000; //result.nroomrate;
   result.orignPrice  = result.nrate; //result.nroomrate;
   var src = $name("weordertasks/csourcename").value || "";
   if (src.indexOf("CHANNEL") >= 0){
      result.ncommissionprice = Math.round(result.nrate * (gCfg && gCfg.commisionRate ? gCfg.commisionRate:list.commisionRate) * 10000)/10000;
   }else{
      result.ncommissionprice = 0;
   }
   return result;
}

//从折扣规则中检查折扣
function getDiscount(priceInfo, vDays, vAmount, memcharge){
   
   //取天数折扣
   var discount = 2;
   for(var i = 0; i < gRules.length; i++){
      if (gRules[i].cCategory == "M"){
         continue;
      }
      
      if (vDays >= gRules[i].ndaysfrom && vDays <= gRules[i].ndaysto && discount > gRules[i].nratediscount){
        discount = gRules[i].nratediscount;
      }
   }
   
   if (discount != 2){
      priceInfo.nratedisount = discount;
   }
   
   //取会员折扣
   discount = 2;
   for(var i = 0; i < gRules.length; i++){
      if (gRules[i].cCategory != "M"){
         continue;
      }
      
      if (memcharge >= gRules[i].ndaysfrom && memcharge <= gRules[i].ndaysto && discount > gRules[i].nratediscount){
        discount = gRules[i].nratediscount;
      }
      
   }
   
   if (discount != 2){
      priceInfo.nmemberdiscount = discount;
   }

}


function sumAmount(){
  //计算总金额
  //计算总计金额
  getTotalAmt("nrate", "txtPriceAmt");
  
  //计算原价格总额
  getTotalAmt("nroomrate", "txtOriginAmt");
  
  
  //计算佣金总额
  getTotalAmt("commision", "txtCommision");
  
  //折扣总额
  var a = Number($id("txtOriginAmt").value), b = Number($id("txtPriceAmt").value), d = Math.round((a - b) * 10000) / 10000;
  $id("txtDiscount").value =  d < 0 ? "0": d + "";
  
  //预付款金额
  $id("txtPrepayAmt").value = Math.round((Number($id("txtPriceAmt").value) * ($id("txtPrepayPercent").value || 0)) * 10000) / 10000 + "";
    
}


function showGressDetail(){
   var grd = $id("gress");
   var ety = grd.getActiveEntity();
   
   //将详细信息写到入住信息上
   //initWriteBackEvt(false);
   var ele, val;
   for(var i = 0; i < gCheckFields.length; i++){
      ele = $id("gres" + gCheckFields[i]);
      if (ele){
         if (ele.setValue){
            ele.setValue(ety.getPropertyByFieldName(gCheckFields[i]) || "");
         }else{
            ele.value = ety.getPropertyByFieldName(gCheckFields[i]) || "";
         }
         
      }
   }
   setCheckinInfoReadonly();
   //initWriteBackEvt(true);
}


function synGresEdit(text, value, grid){
  showGressDetail(grid)
  afterGressEdit(text, value, grid);
}

function synGresAdd(e){
  afterGressAdd(e);
  showGressDetail(e);
}
      
function initWriteBackEvt(isBind){
   var func = isBind == true?writeback:null;
   for(var i = 0; i <  gCheckFields.length; i++){
      ele = $id("gres" + gCheckFields[i]);
      if (ele ){
         ele.onchange = func;
      }
   }
}
 
function writeback(setArrDate){
   var grd = $id("gress");
   var ety = grd.getActiveEntity();
   if (!ety){
     return;
   }
   var ele;
   for(var i = 0; i <  gCheckFields.length; i++){
      ele = $id("gres" + gCheckFields[i]);
      if (ele){
         var v = null;
         if (ele.getValue){
            v = ele.getValue();
         }else{
            v = ele.value;
         }
         ety.setPropertyByFieldName(gCheckFields[i], v || "");
      }
   }
   if (setArrDate == true){
     ety.setPropertyByFieldName("darrdate", dateToString(new Date(), "yyyy-MM-dd HH:mm:ss"));
   }
   ety.setPropertyByFieldName("cstatus", "I");
}


//收取房租和房费
function getDespositAndRate(isWalkin){
   //showModal(urlStr, argument, callBack, this.width, this.height, this.left || "", this.top || "", this.dialogTitle)
   // showModalCenter(contextPath + "/common/jsp/msgBox.jsp", [A], null, null, null, "\u93bb\u612e\u305a\u6dc7\u2103\u4f05")
   var token = null;
   
   if (isWalkin == true){
      //如果是直接入住，就计算出所有的房费
     token = {
      walkinFlag:isWalkin,
      amount: getLineAmt(null, $id("gress").getActiveEntity(), 0, 0, null, "nrate"),
      deposit:Math.round(getLineAmt(null, $id("gress").getActiveEntity(), 0, 0, null, "nrate")/1 * gDepositRate * 10000) /10000 + ""
     };
   }
   showModalCenter("OrderMgr/RateAndDeposit.jsp",
                   token,
                   function(args){
                      //将输入的房费和押金写入账单表
                      var eties = $id("gress").getActiveEntity();
                      var s = eties.getProperty("bills");
                      if (s){
                        var p = {
                            itransid:null,
                            iorderid:eties.getPropertyByFieldName("iorderid"),
                            igresid:eties.getPropertyByFieldName("igresid"),
                            iroomid:eties.getPropertyByFieldName("iroomid"),
                            ctransno:null,
                            iitemid:2,
                            citemcode:"RATE",
                            citemdesc:'现金房费',
                            ccategory:"C",
                            nqty:1,
                            ncredit:null,
                            ndebit:args[0].rate.amount,
                            creferenceno:null,
                            dbusinessdate:dateToString(toBusinessDate(new Date())),
                            cremarks:args[0].rate.remark,
                            isourcetransid:null,
                            ibatchid:null,
                            cdescription:args[0].rate.remark,
                            cshift:null,
                            dcreated:null,
                            ccreatedby:null,
                            cstatus:'O'                 
                        };
                        s.addEntity(Json2Entity(p));
                        p = {
                            itransid:null,
                            iorderid:eties.getPropertyByFieldName("iorderid"),
                            igresid:eties.getPropertyByFieldName("igresid"),
                            iroomid:eties.getPropertyByFieldName("iroomid"),
                            ctransno:null,
                            iitemid:4,
                            citemcode:"DEPOSIT",
                            citemdesc:'押金',
                            ccategory:"C",
                            nqty:1,
                            ncredit:null,
                            ndebit:args[0].desposit.amount,
                            creferenceno:null,
                            dbusinessdate:dateToString(toBusinessDate(new Date())),
                            cremarks:args[0].desposit.remark,
                            isourcetransid:null,
                            ibatchid:null,
                            cdescription:args[0].desposit.remark,
                            cshift:null,
                            dcreated:null,
                            ccreatedby:null,
                            cstatus:'O'                 
                        };
                        s.addEntity(Json2Entity(p));
                        $id("bills").freshFromEntity(eties);
                      }
                   },
                   500,
                   220,
                   "收取房费和押金"
    );
}

//提交账单信息，只需获取新增数据即可
function submitBill(grid){
   
}

function getGresStatus(cellText, ety, rowIdx, cellIdx, grid){
   var cs = ety.getPropertyByFieldName("cstatus");
   if (cs == "R"){
     return "预订";
   }else if (cs == "I"){
      return "在住";
   }else if (cs == "O"){
      return "离店";
   }else if (cs == "N"){
      return "未到";
   }else if (cs == "X"){
      return "取消";
   }
}


function getGresNo(){
  var ety = $id("gress").getActiveEntity();
  if (ety){
    return ety.getPropertyByFieldName("cgresno");
  }else{
    return "";
  }
}

function getRoomNo(){
  var ety = $id("gress").getActiveEntity();
  if (ety){
    return ety.getPropertyByFieldName("roomno");
  }else{
    return "";
  }
}

function checkBillDeposit(){
  var eties = $id("gress").dataset.getAlltEntities();
  for(var i = 0; i < eties.length; i++){
     var rates = eties[i].getProperty("bills");
     if (!rates){
        alert("房间" +  eties[i].getProperty("roomno") + "没有收取房费和押金");
        $id("gress").selectRow(Number($id("gress").getRowAt(i).getAttribute("__entity_rowno")));
        return false;
     }
     
     var ratesEty = rates.getAlltEntities();
     if (!ratesEty || ratesEty.length == 0){
        alert("房间" +  eties[i].getProperty("roomno") + "没有收取房费和押金");
        $id("gress").selectRow(Number($id("gress").getRowAt(i).getAttribute("__entity_rowno")));
        return false;
    }
    
     var rateVal = 0, depositVal = 0;
     for(var j = 0; j < ratesEty.length; j++){//检查账单房费金额是否为0或不存在
        var prop =  ratesEty[j].getPropertyByFieldName("citemcode");
        var dcFlag = ratesEty[j].getPropertyByFieldName("ccategory");
        if (prop == "DEPOSIT"){
           if (dcFlag == "D"){
              depositVal += Number(ratesEty[j].getPropertyByFieldName("ndebit"));
           }else if (dcFlag == "C"){
              depositVal -= Number(ratesEty[j].getPropertyByFieldName("ncredit"));
           }
        }else if (prop == "ROOMRATE"){
           if (dcFlag == "D"){
              rateVal += Number(ratesEty[j].getPropertyByFieldName("ndebit"));
           }else if (dcFlag == "C"){
              rateVal -= Number(ratesEty[j].getPropertyByFieldName("ncredit"));
           }
        }
     }
     if (rateVal <= 0.0001 || depositVal <= 0.0001){
        alert("房间" +  eties[i].getProperty("roomno") + "没有收取房费和押金");
        $id("gress").selectRow(Number($id("gress").getRowAt(i).getAttribute("__entity_rowno")));
        return false;        
     }
  }
}


function getAccountAmt(cellText, ety, rowIdx, cellIdx, grid){
   var credit = ety.getPropertyByFieldName("ncredit");
   var dedit = ety.getPropertyByFieldName("ndebit");
   return credit?credit:dedit;
}


function submitBill4Ajax(){
   //通过Ajax方式产生

}

//取选择的账单数据
function getSelectBills(){
   var x = $id("bills").dataset.getAlltEntities();
   var result = [];
   for(var i = 0; i < x.length; i++){
      if ((x[i].getPropertyByFieldName("isselect") + "").toUpperCase() == "Y"){
        result[result.length] = x[i];
      }
   }
   return result;
}

//处理入账、结账操作
function handlerOperator(item){
  if (!item) return;
  if (item.isConsume){
     var ety = $id("gress").getActiveEntity();
     if (!ety){return;}
     

     var url = "com.hms.OrderMgr.Account.flow?gresId=" + 
               ety.getPropertyByFieldName("igresid") + 
               "&orderId=" + ety.getPropertyByFieldName("iorderid") + 
               (item.itemId?("&itemId=" + item.itemId + "&itemCode=" + item.itemCode + "&itemDesc=" + item.itemDesc):"");
     showModalCenter(url,
                     {
                       loadFunc:reloadBills,
                       convertFunc:toBusinessDate
                     },
                     function(value){
                       //TODO:refresh account info;
                     },
                     500,
                     290,
                     "入账"
                    );
  }else if (item.isComplete == true){//是否结账
     var ety = $id("gress").getActiveEntity();
     if (!ety){return;}
     var url = "com.hms.OrderMgr.Checkout.flow?gresId=" + 
               ety.getPropertyByFieldName("igresid") + 
               "&isAll=" + 
               (item.isAll==true?"Y":"N");
     showModalCenter(url,
                     {
                       loadFunc:reloadBills,
                       convertFunc:toBusinessDate
                     },
                     function(args){
                     
                     },
                     500,
                     290,
                     "结账"
                    );
  }else if (item.isTransfer == true){//转账
     var sel = getSelectBills();
     if (sel.length == 0){
        alert("请选择要转账的账单!");
        return false;
     }
     
     for(var i = 0; i < sel.length; i++){
        var a = sel[i].getPropertyByFieldName("cstatus");
        if (a != "O"){
           alert(sel[i].getPropertyByFieldName("ctransno") + "状态不是未结，不能转账");
           return;
        }
     }
     
     //弹出窗口选择转账订单
     var gresid = $id("gress").getActiveEntity().getPropertyByFieldName("igresid");
     showModalCenter("com.hms.commonPick.WeOrdersVSelect.flow?criteria/_expr[1]/ccategory=A",
                     null,
                     function(args){
                       if (!args || args.length == 0){
                         return;
                       }
                       //转账
                       if (args[0] == gresid){
                          alert('不能转入当前客单!');
                          return;
                       }
                       
                       var token = {
                         srcId:gresid,
                         targetId:args[0],
                         bills:[]
                       };
                       
                       for(var i = 0; i < sel.length; i++){
                         token.bills[token.bills.length] = {
                           itransid:sel[i].getPropertyByFieldName("itransid")
                         };
                       }
                       
                       //发起请求
                       jrq(function(a){
                          reloadBills(gresid);
                          reloadBills(args[0]);                                              
                          }, 
                          "POST", 
                          JSON.stringify(token), 
                          "com.hms.OrderMgr.bills.transferBill.biz.ext", 
                          true);
                     },
                     500,
                     290,
                     "转账"
                    );
  }else if (item.isReverse == true){//是否冲减
     var sel = getSelectBills();
     if (sel.length == 0){
        alert("请选择要冲减的账单!");
        return false;
     }
     
     var bills = [];
     
     for(var i = 0; i < sel.length; i++){
     
        var cs = sel[i].getPropertyByFieldName("cstatus");
        
        //已经冲减的账单不能再次冲减， 
        if (cs != "O"){
           alert("账单" + sel[i].getPropertyByFieldName("ctransno") + "状态不是未结，不能冲减");
           return;
        }
        
        //TODO:i
        /****if (gUser.userId != sel[i].getPropertyByFieldName("ccreatedby")){
           alert("账单只能由入账人进行冲减!");
           return false;
        }***/
        
        bills[bills.length] = {itransid:sel[i].getPropertyByFieldName("itransid")}
     }
     
      //todo:校验密码
      var x = {};
      
      x['bills'] = bills;
      x['bdate'] = dateToString(toBusinessDate(new Date()));
      x['remark'] = prompt("请输入冲减原因");
      if (!x.remark){
         alert("必须输入冲减原因！");
         return;
      }
      
      //执行冲减
      jrq(function(a){
            var rst = eval("(" + a + ")");
            
            //刷新数据集合
            var ety  = $id("gress").getActiveEntity();
            ety.setPropertyByFieldName("bills", Json2Dataset(rst.allBills));
            $id("bills").freshFromEntity(ety);
            calBalanceAmt();
          }, 
          "POST", 
          JSON.stringify(x), 
          "com.hms.OrderMgr.bills.reverseBill.biz.ext", 
          false);
  }else if (item.isWorkAccount == true){//挂工作账
     var sel = getSelectBills();
     if (sel.length == 0){
        alert("请选择要挂账的账单!");
        return false;
     }
     
     for(var i = 0; i < sel.length; i++){
        var a = sel[i].getPropertyByFieldName("cstatus");
        if (a != "O"){
           alert(sel[i].getPropertyByFieldName("ctransno") + "状态不是未结，不能挂账");
           return;
        }
     }
     
     //弹出窗口选择转账订单
     var gresid = $id("gress").getActiveEntity().getPropertyByFieldName("igresid");
     showModalCenter("com.hms.commonPick.Workbook.flow",
                     null,
                     function(args){
                       if (!args || args.length == 0){
                         return;
                       }
                                              
                       var token = {
                         srcId:gresid,
                         targetId:args[0],
                         bills:[]
                       };
                       
                       for(var i = 0; i < sel.length; i++){
                         token.bills[token.bills.length] = {
                           itransid:sel[i].getPropertyByFieldName("itransid")
                         };
                       }
                       
                       //发起请求
                       jrq(function(a){
                          reloadBills(gresid);
                          reloadBills(args[0]);                                              
                          }, 
                          "POST", 
                          JSON.stringify(token), 
                          "com.hms.OrderMgr.bills.creditAccount.biz.ext", 
                          true);
                     },
                     500,
                     290,
                     "挂账"
                    );
  }
}

//绑定入账相关事件
function bindHandlerEvent(){
   var btns = document.getElementsByName("btnHandler");
   for(var i = 0; i < btns.length; i++){
      if (btns[i].addEventListener){
        btns[i].addEventListener("click", function(){
          handlerOperator(gOrderHandler[arguments[0].target.id]);      
        });
      }else{
        btns[i].attachEvent("onclick", function(){
          handlerOperator(gOrderHandler[arguments[0].srcElement.id]);      
        });        
      }
   }
}

//绑定入住信息修改事件
function bindCheckInEvent(){
   var inputs = document.getElementsByName("checkinInfo");
   for(var i = 0; i < inputs.length; i++){
      if (inputs[i].addEventListener){
         inputs[i].addEventListener("change", function(){gCheckInChanged = true;});
      }else{
         inputs[i].attachEvent("onchange", function(){gCheckInChanged = true;});
      }
   }
}



function beforeSelectRow(){
  //如果字段已经发生了修改，就提示用户是否需要保存?
  if (gCheckInChanged == true){
    if (!confirm("您已经修改了入住信息，是否登记入住?")){
       gCheckInChanged = false;;
       return true;
    }
    
    //检查是否可入住
    if (!canCheckIn($id("gress").getActiveEntity())){
      return false;
    }
    
    checkIn($id("gress").getActiveEntity());
    gCheckInChanged = false;
    return false;
  }
}

function afterSelectRow(){
   
   showGressDetail();
   
   var ety = $id("gress").getActiveEntity();
   
   //判断是否显示入住按钮
   var s = ety.getPropertyByFieldName("cstatus");
   
   $id("btnCheckIn").style.display = s == "R"?"":"none";
   $id("btnChangeRoom").style.display = s == "I"?"":"none";
   
   
   var vid = null;
   if ($name("weordertasks/iorderid")){
      vid = $name("weordertasks/iorderid").value || "";
      if (!trim(vid)){
         vid = null;
      }
      
      if (vid){
        vid = ety.getProperty("cgresno") || "";
        if (!trim(vid)){
          vid = null;
        }
      }
   }
   $id("btnMsg").style.display = s != "X" && s != "O" && vid != null?"":"none";
   $id("btnStorage").style.display = s != "X" && s != "O" && vid != null?"":"none";
   $id("btnLoan").style.display = s != "X" && s != "O" && vid != null?"":"none";
   $id("btnLost").style.display = s != "X" && s != "O" && vid != null?"":"none";
   
}

function setCheckinInfoReadonly(){
   var grd = $id("gress");
   var ety = grd.getActiveEntity();
   if (!ety){
     return;
   }
   var isReadonly = ety.getPropertyByFieldName("cstatus") != "R";
   var ele;
   for(var i = 3; i <  gCheckFields.length; i++){
      ele = $id("gres" + gCheckFields[i]);
      if (ele){
         if (ele.setReadOnly){
            ele.setReadOnly(isReadonly);
         }else{
            if (ele.tagName.toUpperCase() == "SELECT"){
              ele.disabled = isReadonly;
            }else{
              ele.readOnly = isReadonly;
            }
         }
      }
   }
}

function calBalanceAmt(){
   $id("txtConsumAmt").value = "";
   $id("txtAccountAmt").value = "";
   $id("txtBalanceAmt").value = "";  
       
   var gres = $id("gress").getActiveEntity();
   var trans = gres.getProperty("bills");
   if (!trans){return;}
   var dst = trans.getAlltEntities();
   var c = 0, a = 0, b = 0, ct;
   for(var i = 0; i < dst.length; i++){
      ct = dst[i].getPropertyByFieldName("ccategory");
      if (ct == "C"){
         if (dst[i].getPropertyByFieldName("ncredit")){
            c += Number(dst[i].getPropertyByFieldName("ncredit"));
         }
      }else{
         if (dst[i].getPropertyByFieldName("ndebit")){
            a += Number(dst[i].getPropertyByFieldName("ndebit"));
         }      
      }
   }
   
   $id("txtConsumAmt").value = a + "";
   $id("txtAccountAmt").value = c + "";
   $id("txtBalanceAmt").value = (c - a) + "";  
   
}

function beforeModifyEdit(cell, cellindex, rowIdx){
   
   var gres = $id("gress").getActiveEntity(), field = $id("gress").activeField, c = gres.getPropertyByFieldName("cstatus");
   if (c !=  "R" && c !=  "N" && field.fieldName != "cnewroomno"){
      return false;
   }
   
   if (c == "O" || c == "X"){
      return false;
   }
   
   return true;
}

function beforeModifyDel(){
  var gres = $id("gress").getActiveEntity();
  var x = gres.getPropertyByFieldName("cgresno") || "";
  if (trim(x)){
     alert("客单" + x + "已经生效，不能删除!");
     return false;
  }
  
  x = gres.getPropertyByFieldName("cmodifystatus");
  if (x != "N" && x != "R"){
    alert("客单不能删除!");
    return false;
  }
  
  return true;
}

function gresChanged(ety){
  var result = false;
  var x, y;
    
  if (ety.getPropertyByFieldName("isourceroomid") != ety.getPropertyByFieldName("inewroomid")){
    return true;
  }
  
  if ((ety.getPropertyByFieldName("biscancelgres") + "").toUpperCase() == "Y"){
    return true;
  }
  
  x = ety.getPropertyByFieldName("dsourcearrdate");
  y = ety.getPropertyByFieldName("dnewarrdate");
     
  if (x != (y + ".0") && x != y){
    return true;
  }

  x = ety.getPropertyByFieldName("dsourcedepdate");
  y = ety.getPropertyByFieldName("dnewdepdate");
  if (x != (y + ".0") && x != y){
    return true;
  }

  return result;
}

function getModifyDesc(cellText, ety, rowIdx, cellIdx, grid){
  var result = "";
  var x, y;
  if (!ety.getPropertyByFieldName("igresid")){
    result = "新增客单";
    return result;
  }else if (!ety.getPropertyByFieldName("igresid")){
    result = "新增客单";
    return result;
  }else {
     if (ety.getPropertyByFieldName("isourceroomid") != ety.getPropertyByFieldName("inewroomid")){
       result += "换房";
       return result;
     }
     
     if ((ety.getPropertyByFieldName("biscancelgres") + "").toUpperCase() == "Y"){
        return "取消订房";
     }
     
     x = ety.getPropertyByFieldName("dsourcearrdate");
     y = ety.getPropertyByFieldName("dnewarrdate");
     
     if (x != (y + ".0") && x != y){
       result += ";修改抵店日期";
     }

     x = ety.getPropertyByFieldName("dsourcedepdate");
     y = ety.getPropertyByFieldName("dnewdepdate");
     if (x != (y + ".0") && x != y){
       result += ";修改离店日期";
     }
     
     if (result == ""){
        return "未修改";
     }else{
        return result;
     }
  }
}

function getGresStatus(cellText, ety, rowIdx, cellIdx, grid){
  var result = ety.getPropertyByFieldName("cstatus");
  if (result == "R"){
    return "预订";
  }else if (result == "I"){
    return "在住";
  }else if (result == "O"){
    return "离店";
  }else if (result == "N"){
    return "未到";
  }else if (result == "X"){
    return "取消";
  }
}

function validateOrder(isCheckLimitDays){
   var isOut = false, isLimit = false;
   if ($name("weordertasks/bispickup")){
     var ispickup  = $name("weordertasks/bispickup").value;
     if ((ispickup + "").toUpperCase() == "Y"){
        var pickdate = $name("weordertasks/dpickupdate").value || "";
        var pickaddress = $name("weordertasks/cpickupaddress").value || "";
        var seecount = $name("weordertasks/seeoffcounter").value || "";
        if (!trim(pickdate) || !trim(pickaddress) || !trim(seecount)){
         alert("需要接机时，请填写接机时间，接机地点，接机人数");
         return false;
        }
     }
   }
   
   var isseeoff  = $name("weordertasks/bisseeoff").value;
   if ((isseeoff + "").toUpperCase() == "Y"){
      var offDate = $name("weordertasks/dseeoffdate").value;
      var offAddress = $name("weordertasks/cseeoffaddress").value;
      if (!trim(offDate) || !trim(offAddress)){
         alert("需要送机时，请填写送机时间，送机目的地!");
         return false;
      }      
   }
   
   var allEty = $id("gress").dataset.getAlltEntities();
   var removeEty = $id("gress").dataset.getRemovedEntities();
   if (allEty.length - removeEty.length <= 0){
      alert("请填写客单信息");
      return false;
   }
   
   var src = $name("weordertasks/csourcename").value;
   for(var i = 0; i < allEty.length; i++){
   
      if (allEty[i].status == Entity.STATUS_DELT || allEty[i].status == Entity.STATUS_HIDDEN){
         continue;
      }
      
      var iroom = allEty[i].getPropertyByFieldName("iroomid") || "";
      if (!trim(iroom)){
         alert("房号不能为空!");
         return false;
      }
      
      iroom = allEty[i].getPropertyByFieldName("arrorigdate") || "";
      if (!trim(iroom)){
         alert("预计抵店日期不能为空!");
         return false;
      }   
      
      
      var vd = allEty[i].getPropertyByFieldName("deporigdate") || "";
      if (!trim(vd)){
         alert("预计离店日期不能为空!");
         return false;
      }    
      
      var x = stringToDate(iroom, 'yyyy-MM-dd HH:mm:ss').getTime(), y = stringToDate(vd, 'yyyy-MM-dd HH:mm:ss').getTime();
      if (x > y){
        alert("预计抵店日期必须小于预计离店日期");
         return false;        
      }
      
      var m = new Date();
      if (x < (m.getTime() - 1*60*60*1000)){
         alert("预计抵店日期必须大于当前日期");
         return false;        
      }
          
      if (y < m.getTime() - 30000){
         alert("预计离店日期必须大于当前日期");
         return false;        
      }   
      
      
      if　(src != "WalkIn"){
      var schedule = allEty[i].getPropertyByFieldName("schedules");
      if (schedule){
        var schEties = getDatasetEntities(schedule), ic = 0;
        for(var j = 0; j < schEties.length; j++){
           if (schEties[j].status == Entity.STATUS_DELT || schEties[j].status == Entity.STATUS_HIDDEN){
             continue;
           }
           ic++;
        }
        
        var days = getLimitDays();
        if (ic < days){
           isLimit = true;
        }else{
           isOut = true;
        }
      }}
      
      //检查是否已经被预定
      x = getGress(allEty[i].getProperty("localkey"));
      if (x.errCode == "E"){
         alert("房号" + allEty[i].getProperty("roomno") + '在指定日期范围内已经被客单' + x.errMsg + '占用，不能预订!');
         return false;
      }                     
   }
   
   if (isCheckLimitDays == true){
   if (isLimit == true && isOut == true){
      alert("预定天数少于" + getLimitDays() + "天的客单必须单独维护一张订单.");
      return false;
   }else if (isLimit == true){
      if (!confirm("预定天数少于三天，需要走VIP审批流程，是否继续?")){
        return false;
      }
   }
   }

   
   return true;
}


function getDepDate(cellText, ety, rowIdx, cellIdx, grid){
  var x = ety.getProperty("ddepdate") || "";
  if (!trim(x)){
     x = ety.getProperty("deporigdate") + "(预计)";
  }
  return x.replace(".0", "");
}

function getArrDate(cellText, ety, rowIdx, cellIdx, grid){
  var x = ety.getProperty("darrdate") || "";
  if (!trim(x)){
     x = ety.getProperty("arrorigdate") + "(预计)";
  }
  return x.replace(".0", "");
}

//客户留言
function guestMsg(){
  guestHandle("com.hms.OrderMgr.WeGuesmessageMaintain.flow");
}

//物品寄存
function guestStorage(){
  guestHandle("com.hms.OrderMgr.WeMaterialstorageMaintain.flow");
}

//商品租借
function guestLoan(){
  guestHandle("com.hms.OrderMgr.MaterialLoan.flow");
}

//物品遗留登记
function guestLost(){
  guestHandle("com.hms.OrderMgr.WeMateriallostMaintain.flow");
}

function guestHandle(url){
  var ety =  $id("gress").getActiveEntity(); 
  window.open(url +
                         "?gresid=" + (ety.getProperty("igresid")?ety.getProperty("igresid"):"") + 
                         "&gresno=" + (ety.getProperty("cgresno")?ety.getProperty("cgresno"):"") + 
                         "&roomid=" + (ety.getProperty("iroomid")?ety.getProperty("iroomid"):"") + 
                         "&roomno=" + (ety.getProperty("roomno")?ety.getProperty("roomno"):"") + 
                         "&guestname=" + (ety.getProperty("cguestname")?ety.getProperty("cguestname"):"") + 
                         "&_eosFlowAction=insert");  
}


function getSummary(cellText, ety, rowIdx, cellIdx, grid){
   var a = ety.getProperty("ncommissionprice")||"0",
       b = ety.getProperty("nrate")||"0";
       
   return Math.round((a * 1 + b * 1) * 10000)/10000 + "";
}


function getBillStatusName(cellText, ety, rowIdx, cellIdx, grid){
  var x = ety.getProperty("cstatus");
  if (x == 'O'){
    return '未结';
  }
  
  if (x == 'F'){
    return '已结';
  }
    
  if (x == 'C'){
    return '转账';
  }
      
  if (x == 'E'){
    return '冲减';
  }
        
}

function changeRoom(){
   var ety =  $id("gress").getActiveEntity();
   if (!ety){
     return;
   }
   
   showModalCenter("com.hms.OrderMgr.changeRoom.flow?oldgres/igresid=" + ety.getProperty("igresid"),
                   null,
                   function(args){
                     if (!args || !args[0]){
                        return;
                     }
                     
                     var param = {
                       oldgres:{igresid:ety.getProperty("igresid")},
                       gres:{igresid:args[0]}
                       
                     }
                     //重新查询客单信息，并进行显示
                     //
                     jrq(function(a){
                       //设置客单的离店日期、状态
                       var vals = eval("(" + a + ")");
                       ety.setProperty("darrdate", a.oldgres.darrdate);
                       ety.setProperty("cstatus", a.oldgres.cstatus);
                       
                       //设置房租计划/账单
                       ety.setProperty("schedules", a.oldgres.schedules);
                       ety.setProperty("bills", a.oldgres.bills);
                       
                       //显示新的客单
                       var newety = Json2Entity(a.gres);
                       $("gress").dataset.addEntity(newety, false);
                       
                       //TODO:重新计算金额、显示内容

                     }, 
                     "POST", 
                     JSON.stringify(param), 
                     "com.hms.OrderMgr.orderAjax.afterChangeRoom.biz.ext", 
                     false);
                   },
                   900,
                   480,
                   "换房"
    );
}


function showScheduleStatus(cellText, ety, rowIdx, cellIdx, grid){
  var x = ety.getProperty("cstatus");
  if (x == "B"){
     return "预订";
  }else if (x == "O"){
     return "入住";
  }else if (x == "C"){
     return "取消";  
  }else{
     return "";
  }
}

function skipDate(cellText, ety, rowIdx, cellIdx, grid){

  var x = cellText;
  if (!cellText || cellText == ""){
     return "";
  }
  
  return dateToString(stringToDate(cellText, "yyyy-MM-dd HH:mm"), 'yyyy-MM-dd HH:mm');
}

function customSrcChange(){
   var src = $name("weordertasks/csourcename").value || "", hasComm = false;
   if (src.indexOf("CHANNEL") >= 0){//如果是渠道，则预付价格为0
      $name("weordertasks/npaypercent").value = "0";
      hasComm = true;
   }else{
      $id("txtPrepayPercent").value = gCfg.PREPAY_PERCENT + "";
   }
   //刷新预付金额
   $id("txtPrepayAmt").value = Math.round((Number($id("txtPriceAmt").value || "0") * $name("weordertasks/npaypercent").value) * 10000) / 10000 + "";
   
   //刷新佣金
   var dataset = $id("gress").dataset, entities = getDatasetEntities(dataset);
   for(var i = 0; i < entities.length; i++){
     if (entities[i].status == Entity.STATUS_DELT || entities[i].status == Entity.STATUS_HIDDEN){
        continue;
     }
     
     var schedule = entities[i].getPropertyByFieldName("schedules");
     if (!schedule){
       continue;
     }
   
     var schEties = getDatasetEntities(schedule);
     for(var j = 0; j < schEties.length; j++){
        if (hasComm == false){
          schEties[j].setPropertyByFieldName("ncommissionprice", "0");
        }else{
          schEties[j].setPropertyByFieldName("ncommissionprice", Math.round(schEties[j].getProperty("nrate") * (gCfg && gCfg.commisionRate ? gCfg.commisionRate: 0.05) * 10000)/10000);
        }
     }
  }
  
  //计算佣金总额
  getTotalAmt("commision", "txtCommision");
     
}


function getLimitDays(){
  if (!gCfg){return 3};
  return gCfg.LIMIT_DAYS || 3;
}